package com.chanjiedata.changbs.module.main;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseActivity;
import com.chanjiedata.changbs.base.MainApplication;
import com.chanjiedata.changbs.help.ImageHelper;
import com.chanjiedata.changbs.help.PermissionHelper;
import com.chanjiedata.changbs.module.count.CountFragment;
import com.chanjiedata.changbs.module.login.LoginActivity;
import com.chanjiedata.changbs.module.mine.MineFragment;
import com.chanjiedata.changbs.module.mine.RenZhenActivity;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Index;
import com.chanjiedata.changbs.utlis.APKVersionCodeUtils;
import com.chanjiedata.changbs.utlis.DialogUtils;
import com.chanjiedata.changbs.utlis.StatusBarUtil;
import com.chanjiedata.changbs.view.NoScrollViewPager;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseActivity {

    @BindView(R.id.viewPagers)
    NoScrollViewPager viewPager;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;


    private long mExitTime;
    public String tureeName = "";
    CountFragment count;
    private int INSTALL_PERMISS_CODE = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        StatusBarUtil.setTranslucentStatus(this);
        ButterKnife.bind(this);
        initMenus();
        initView();
        checkVersion();
        MainApplication.addTempActivity(this);

    }

    String[] tabNames;
    int[] tabIcons;

    private void initMenus() {
        tabNames = getResources().getStringArray(R.array.main_tabs);
        TypedArray ar = getResources().obtainTypedArray(R.array.main_tab_icons);
        int len = ar.length();
        tabIcons = new int[len];
        for (int i = 0; i < len; i++) {
            tabIcons[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
    }

    private void initView() {
        tureeName = getIntent().getStringExtra("trueName");
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(count = new CountFragment());
        fragments.add(new QrCodeFragment());
        fragments.add(new MineFragment());
        viewPager.setOffscreenPageLimit(4);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return null;
            }

        });
        //设置图标
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabNames.length; i++) {
            tabLayout.getTabAt(i).setCustomView(getTabView(tabNames[i], tabIcons[i]));
        }

        // 设置监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    public View getTabView(String tabName, int tabIcon) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.tab_layout, null);
        ImageView iv_tab = view.findViewById(R.id.iv_tab);
        TextView tv_tab = view.findViewById(R.id.tv_tab);
        iv_tab.setImageResource(tabIcon);
        tv_tab.setText(tabName);
        return view;
    }

    //返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                MainApplication.finishAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void checkVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                checkVerison(response);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });

    }

    private void checkVerison(byte[] response) {
        String versionName = APKVersionCodeUtils.getVerName(mContext);
        Index.get_app_version_info versionBean = null;
        try {
            versionBean = Index.get_app_version_info.parseFrom(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        Log.e("mango", "checkVerison: " + versionBean);
        float serviceVersion = Float.parseFloat(versionBean.getVersion());
        float locationeVersion = Float.parseFloat(versionName);
        if (locationeVersion < serviceVersion) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = this.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(mContext);
                    builder.setTitle("提示");
                    builder.setMessage("请允许安装未知来源权限");
                    builder.setCancelable(false);
                    builder.setOnDismissListener(dialog -> {
                    });
                    builder.setNegativeButton("", (dialog, which) -> {

                    });
                    builder.setPositiveButton("设置", (dialog, which) -> {
                        startInstallPermissionSettingActivity();
                        finish();
                    });
                    builder.show();
                } else {
                    AllenVersionChecker instance = AllenVersionChecker.getInstance();
                    DownloadBuilder downloadBuilder = instance.downloadOnly(
                            UIData.create().setDownloadUrl(versionBean.getDownloadUrl()).setTitle(versionBean.getTitle()).setContent(versionBean.getContext()));
                    if (versionBean.getForce().equals("1")) {
                        downloadBuilder.setForceUpdateListener(MainApplication::finishAllActivity);
                    }
                    downloadBuilder.setForceRedownload(true).executeMission(mContext);
                }
            } else {
                AllenVersionChecker instance = AllenVersionChecker.getInstance();
                DownloadBuilder downloadBuilder = instance.downloadOnly(
                        UIData.create().setDownloadUrl(versionBean.getDownloadUrl()).setTitle(versionBean.getTitle()).setContent(versionBean.getContext()));
                if (versionBean.getForce().equals("1")) {
                    downloadBuilder.setForceUpdateListener(MainApplication::finishAllActivity);
                }
                downloadBuilder.setForceRedownload(true).executeMission(mContext);
            }
        }
    }


    /**
     * 开启安装未知来源权限
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, INSTALL_PERMISS_CODE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("mango", "onDestroy: ");
    }



}
